<template>
  <div 
    :class="[
      'menu-container',
      `${prefixCls}-bg`
    ]"
  >
    <!-- 左侧菜单树 -->
    <div class="menu-left">
      <el-input
        v-model="searchKeyword"
        placeholder="输入关键字进行过滤"
        prefix-icon="Search"
        clearable
      />
      <el-tree
        ref="menuTree"
        :data="filteredMenuList"
        :props="{ label: 'menuName' }"
        node-key="id"
        highlight-current
        draggable
        :allow-drop="handleAllowDrop"
        :allow-drag="handleAllowDrag"
        @node-drop="handleDrop"
        @node-click="handleNodeClick"
        show-checkbox
        @check="handleCheck"
        :filter-node-method="filterNode"
      />
      <div class="tree-actions">
        <el-button type="primary" @click="handleAddRootMenu">添加根菜单</el-button>
        <el-button 
          type="danger" 
          :disabled="!checkedMenus.length"
          @click="handleBatchDelete"
        >
          删除选中
        </el-button>
      </div>
    </div>

    <!-- 中间菜单配置 -->
    <div class="menu-center">
      <div class="form-header">
        <span class="title">{{ formData.id ? '编辑菜单' : '新增菜单' }}</span>
        <div class="actions">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="显示名称" prop="menuName">
          <el-input v-model="formData.menuName" placeholder="请输入显示名称" />
        </el-form-item>

        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="formData.parentId"
            :data="menuTreeData"
            :props="{ label: 'menuName', value: 'id' }"
            placeholder="请选择上级菜单"
          />
        </el-form-item>

        <el-form-item label="类型">
          <el-radio-group v-model="formData.menuType">
            <el-radio-button :value="1">菜单</el-radio-button>
            <el-radio-button :value="2">iframe</el-radio-button>
            <el-radio-button :value="3">外链</el-radio-button>
            <el-radio-button :value="4">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="别名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入别名" />
          <div class="form-tips">系统唯一且只允许英文</div>
        </el-form-item>

        <el-form-item label="菜单图标">
          <el-input v-model="formData.icon">
            <template #append>
              <el-button @click="handleIconSelect">选择图标</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="路由地址" prop="routePath">
          <el-input v-model="formData.routePath" placeholder="/system/menu" />
        </el-form-item>

        <el-form-item label="重定向" v-if="formData.menuType === 1">
          <el-input v-model="formData.redirect" placeholder="请输入重定向地址" />
        </el-form-item>

        <el-form-item label="菜单高亮">
          <el-input v-model="formData.activeMenu" placeholder="请输入菜单高亮路径" />
          <div class="form-tips">子菜单或详情页需要高亮左侧菜单时配置</div>
        </el-form-item>

        <el-form-item label="视图">
          <el-input v-model="formData.component" placeholder="views/system/menu" />
          <div class="form-tips">如果不是，链接跳转iframe等无需视图的菜单，请不需填写</div>
        </el-form-item>

        <el-form-item label="是否隐藏">
          <el-radio-group v-model="formData.hidden">
            <el-radio :value="false">显示菜单</el-radio>
            <el-radio :value="true">隐藏菜单</el-radio>
          </el-radio-group>
          <div class="form-tips">菜单不显示在左侧菜单中，但用户依然可以访问</div>
        </el-form-item>

        <el-form-item label="是否启用">
          <el-switch v-model="formData.status" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 右侧权限配置 -->
    <div class="menu-right">
      <div class="right-header">
        <span class="title">接口权限</span>
        <el-button type="primary" size="small" @click="handleAddPermission">新增</el-button>
      </div>
      <el-table :data="permissionList" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="标识">
          <template #default="{ row }">
            <el-input v-model="row.name" placeholder="请输入标识" />
          </template>
        </el-table-column>
        <el-table-column prop="description" label="权限描述">
          <template #default="{ row }">
            <el-input v-model="row.description" placeholder="请输入描述" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditPermission(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDeletePermission(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  ElInput,
  ElTree,
  ElButton,
  ElForm,
  ElFormItem,
  ElTreeSelect,
  ElRadioGroup,
  ElRadioButton,
  ElRadio,
  ElSwitch,
  ElTable,
  ElTableColumn
} from 'element-plus'

// 使用与 analytics 相同的前缀方式
const prefixCls = 'app'

// 定义菜单项接口
interface MenuItem {
  id: number
  menuName: string
  icon?: string
  routePath?: string
  menuType?: number
  children?: MenuItem[]
}

// 初始化菜单数据
const menuList = ref<MenuItem[]>([
  {
    id: 1,
    menuName: '系统管理',
    children: [
      {
        id: 11,
        menuName: '用户管理',
        routePath: '/system/user',
        menuType: 1,
        icon: 'User'
      },
      {
        id: 12,
        menuName: '角色管理',
        routePath: '/system/role',
        menuType: 1,
        icon: 'UserFilled'
      },
      {
        id: 13,
        menuName: '菜单管理',
        routePath: '/system/menu',
        menuType: 1,
        icon: 'Menu'
      }
    ]
  },
  {
    id: 2,
    menuName: '场所管理',
    icon: 'Location',
    routePath: '/place'
  },
  {
    id: 3,
    menuName: '盒子客户端管理',
    icon: 'Box',
    routePath: '/box'
  },
  {
    id: 4,
    menuName: '区域配置',
    icon: 'Map',
    routePath: '/area'
  },
  {
    id: 5,
    menuName: '合作应用管理V2',
    icon: 'Connection',
    routePath: '/app/v2'
  },
  {
    id: 6,
    menuName: '合作应用管理',
    icon: 'Connection',
    routePath: '/app'
  },
  {
    id: 7,
    menuName: '三方应用(ad)',
    icon: 'Share',
    routePath: '/third-party'
  }
])

// 初始化树形数据
const menuTreeData = ref([
  { 
    id: 0, 
    menuName: '根菜单',
    children: menuList.value 
  }
])

// 右侧权限列表
const permissionList = ref([
  {
    id: 1,
    name: 'settingMenu.edit',
    description: '菜单修改'
  },
  {
    id: 2,
    name: 'settingMenu.dele',
    description: '菜单删除'
  },
  {
    id: 3,
    name: 'settingMenu.list',
    description: '菜单查看'
  }
])

// 表单相关
const formRef = ref<FormInstance>()

interface MenuFormData {
  id: string
  menuName: string
  parentId: number
  menuType: number | string
  name: string
  alias: string
  icon: string
  routePath: string
  redirect: string
  viewPath: string
  component: string
  activeMenu: string
  keepAlive: boolean
  hidden: boolean
  status: boolean
}

const formData = ref<MenuFormData>({
  id: '',
  menuName: '',
  parentId: 0,
  menuType: 1,
  name: '',
  alias: '',
  icon: '',
  routePath: '',
  redirect: '',
  viewPath: '',
  component: '',
  activeMenu: '',
  keepAlive: false,
  hidden: false,
  status: true
})

// 表单验证规则
const rules = {
  menuName: [{ required: true, message: '请输入显示名称', trigger: 'blur' }],
  routePath: [{ required: true, message: '请输入路由地址', trigger: 'blur' }]
}

// 加载菜单数据
const loadMenuData = async () => {
  try {
    // 模拟接口返回的数据
    menuList.value = [
      {
        id: 1,
        menuName: '首页',
        icon: 'House',
        routePath: '/'
      },
      {
        id: 2,
        menuName: '系统管理',
        icon: 'Setting',
        children: [
          {
            id: 21,
            menuName: '菜单管理',
            routePath: '/system/menu',
            menuType: 1,
            icon: 'Menu'
          },
          {
            id: 22,
            menuName: '用户管理',
            routePath: '/system/user',
            menuType: 1,
            icon: 'User'
          },
          {
            id: 23,
            menuName: '角色管理',
            routePath: '/system/role',
            menuType: 1,
            icon: 'UserFilled'
          }
        ]
      },
      {
        id: 3,
        menuName: '场所管理',
        icon: 'Location',
        routePath: '/place'
      },
      {
        id: 4,
        menuName: '盒子客户端管理',
        icon: 'Box',
        routePath: '/box'
      },
      {
        id: 5,
        menuName: '区域配置',
        icon: 'Map',
        routePath: '/area'
      },
      {
        id: 6,
        menuName: '合作应用管理V2',
        icon: 'Connection',
        routePath: '/app/v2'
      },
      {
        id: 7,
        menuName: '合作应用管理',
        icon: 'Connection',
        routePath: '/app'
      },
      {
        id: 8,
        menuName: '三方应用(ad)',
        icon: 'Share',
        routePath: '/third-party'
      }
    ]

    // 初始化树形选择数据
    menuTreeData.value = [
      {
        id: 0,
        menuName: '根菜单',
        children: menuList.value
      }
    ]
  } catch (error) {
    console.error('加载菜单数据失败:', error)
    ElMessage.error('加载菜单数据失败')
  }
}

interface MenuNode {
  id: string
  menuName: string
  parentId: number
  menuType: number | string
  name?: string
  alias?: string
  icon?: string
  routePath?: string
  redirect?: string
  viewPath?: string
  component?: string
  activeMenu?: string
  keepAlive?: boolean
  hidden?: boolean
  status?: boolean
}

const handleNodeClick = (node: MenuNode) => {
  if (!node) return
  formData.value = { 
    ...formData.value, 
    ...node,
    hidden: node.hidden || false,
    status: node.status ?? true
  }
  loadPermissionList(node.id)
}

// 加载权限列表
const loadPermissionList = async (menuId: string) => {
  try {
    // TODO: 调用接口获取权限列表
    permissionList.value = []
  } catch (error) {
    console.error('加载权限列表失败:', error)
    ElMessage.error('加载权限列表失败')
  }
}

// 添加权限
const handleAddPermission = () => {
  permissionList.value.push({
    id: Date.now(), // 临时 ID
    name: '',
    description: ''
  })
}

// 编辑权限
const handleEditPermission = (row: any) => {
  // TODO: 实现编辑权限的功能
  console.log('编辑权限:', row)
}

// 删除权限
const handleDeletePermission = (row: any) => {
  const index = permissionList.value.findIndex(item => item.id === row.id)
  if (index > -1) {
    permissionList.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  try {
    // TODO: 调用保存接口
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 处理重置
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 处理图标选择
const handleIconSelect = () => {
  // TODO: 实现图标选择功能
  ElMessage.info('图标选择功能开发中...')
}

// 树形组件引用
const menuTree = ref()

// 选中的菜单项
const checkedMenus = ref<number[]>([])

// 处理拖拽
const handleAllowDrop = (draggingNode: any, dropNode: any, type: 'prev' | 'inner' | 'next') => {
  // 允许所有拖拽
  return true
}

const handleAllowDrag = (node: any) => {
  // 允许所有节点拖拽
  return true
}

const handleDrop = (draggingNode: any, dropNode: any, type: string) => {
  // 更新菜单顺序
  const draggingData = draggingNode.data
  const dropData = dropNode.data

  // TODO: 调用接口保存新的菜单顺序
  ElMessage.success('菜单排序已更新')
}

// 处理选中
const handleCheck = (node: any, checkedInfo: any) => {
  checkedMenus.value = checkedInfo.checkedKeys
}

// 添加根菜单
const handleAddRootMenu = () => {
  const newMenu = {
    id: Date.now(),
    menuName: '新建菜单',
    menuType: 1,
    parentId: 0,
    icon: '',
    routePath: '',
    status: true
  }
  
  menuList.value.push(newMenu)
  ElMessage.success('添加成功')
}

// 批量删除
const handleBatchDelete = async () => {
  if (!checkedMenus.value.length) return
  
  try {
    // TODO: 调用接口删除选中的菜单
    const deleteMenus = (list: any[]) => {
      for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i]
        if (checkedMenus.value.includes(item.id)) {
          list.splice(i, 1)
        } else if (item.children?.length) {
          deleteMenus(item.children)
        }
      }
    }
    
    deleteMenus(menuList.value)
    checkedMenus.value = []
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 搜索关键字
const searchKeyword = ref('')

// 过滤后的菜单数据
const filteredMenuList = computed(() => {
  if (!searchKeyword.value) {
    return menuList.value
  }

  const keyword = searchKeyword.value.toLowerCase()
  
  // 递归搜索菜单
  const filterNodes = (nodes: any[]): any[] => {
    return nodes.reduce((filtered: any[], node) => {
      const matchesKeyword = node.menuName.toLowerCase().includes(keyword)
      
      if (node.children?.length) {
        const filteredChildren = filterNodes(node.children)
        if (filteredChildren.length) {
          filtered.push({
            ...node,
            children: filteredChildren
          })
          return filtered
        }
      }
      
      if (matchesKeyword) {
        filtered.push({ ...node })
      }
      
      return filtered
    }, [])
  }

  return filterNodes(menuList.value)
})

// 页面加载时初始化数据
loadMenuData()

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.menuName.toLowerCase().includes(value.toLowerCase())
}
</script>

<style lang="less" scoped>
.menu-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color);
}

// 使用与 analytics 相同的背景类
:global(.app-bg) {
  background-color: var(--el-bg-color) !important;
}

.menu-left {
  width: 250px;
  border-right: 1px solid var(--el-border-color-light);
  padding-right: 20px;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color);
  
  :deep(.el-tree) {
    background-color: transparent;
    flex: 1;
    overflow: auto;
    margin: 10px 0;
  }

  :deep(.el-input__wrapper),
  :deep(.el-tree),
  :deep(.el-tree-node__content) {
    background-color: var(--el-bg-color);
  }
}

.menu-center {
  flex: 1;
  min-width: 500px;
  background-color: var(--el-bg-color);

  :deep(.el-form-item__label) {
    color: var(--el-text-color-primary);
  }

  :deep(.el-input__wrapper),
  :deep(.el-radio-button__inner),
  :deep(.el-switch) {
    background-color: var(--el-bg-color);
  }
}

.menu-right {
  width: 400px;
  border-left: 1px solid var(--el-border-color-light);
  padding-left: 20px;
  background-color: var(--el-bg-color);

  :deep(.el-table) {
    background-color: var(--el-bg-color);
    
    th.el-table__cell {
      background-color: var(--el-bg-color);
    }
    
    .el-table__cell {
      background-color: var(--el-bg-color);
    }
  }
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-header .title {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.form-tips {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.right-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.right-header .title {
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.tree-actions {
  display: flex;
  gap: 10px;
  padding-top: 10px;
  border-top: 1px solid var(--el-border-color-light);
  
  .el-button {
    flex: 1;
  }
}
</style> 
